const path = require('path');
const webpack = require('webpack');
const ROOT = process.cwd();  // 根目录
const ENV = process.env.NODE_ENV;
const IsProduction = (ENV === 'production') ? true : false;

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PostcssConfigPath = './config/postcss.config.js';
const Glob = require('glob');
const HappyPack = require('happypack');
const HappyThreadPool = HappyPack.ThreadPool({ size: (IsProduction ? 10 : 4) });
const CopyWebpackPlugin = require('copy-webpack-plugin');

const MyPlugin = require('./myplugin')

const pubConfig = '/imgotv-miniv6/';

const staticImg = IsProduction ? '//img.mgtv.com' + pubConfig : '/';
const publicPath = IsProduction ? '//js.mgtv.com' + pubConfig : '/';
const staticCss = IsProduction ? '//css.mgtv.com' + pubConfig : '/';

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
//const ProgressPlugin = require('@fedor/progress-webpack-plugin')
const HtmlWebpackExtPlugin = require('html-webpack-ext-plugin')
const { getEntryList, getViewPages, fssConfigSync } = require('fss-webpack-utils');

const global = require('@fedor/global');
const resolve = dir => path.resolve(__dirname, '..', dir)

const CDN = {
	img: staticImg,
	js: publicPath,
	css: staticCss
}

const resolveModules = [
	resolve('src'),
	resolve('node_modules')
]

//js路径
const entries = getEntryList({
	globPath: [
		'./src/js/*/{,!(source|_*|lib|router|pages)/**}/!(_*).js'
	],
	rebaseTo: './src/js'
});

//页面路径
const pages = getViewPages({
	entries,
	commonChunks: ['common', 'runtime'],//公共JS
	globPath: [
		'./src/view/**/{,!(_*|source|shared)}/!(_*).{html,ejs}'
	],
	rebaseTo: './src/view',
	pathRewrite: {
		'(.*)': './view/$1'
	}
});

let configPlugins = [
	new HtmlWebpackExtPlugin({ cache: true, delimiter: '$', locals: {} }),
	//new ProgressPlugin(),
	new webpack.ProvidePlugin({ $: 'jquery', Vue: 'vue', _: 'lodash' }),
	//new FriendlyErrorsWebpackPlugin({ clearConsole: false }),
	new webpack.optimize.ModuleConcatenationPlugin(),
	new webpack.optimize.CommonsChunkPlugin({//将node_modules里的依赖都打进common中
		name: 'common',
		minChunks: module => module.context && module.context.includes('node_modules')
	}),
	new webpack.optimize.CommonsChunkPlugin({
		name: 'runtime',
		minChunks: 3
	}),
	// @see https://github.com/webpack/webpack/tree/master/examples/multiple-entry-points-commons-chunk-css-bundle
	new ExtractTextPlugin({
		filename: 'css/[name].css?[contenthash:8]',
		allChunks: true
	}),
	...pages,
	new MyPlugin({ options: CDN })
];

if (IsProduction) {
    configPlugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false,
            drop_console: true,
            pure_funcs: ['console.log']
        }
    }));
}


// 配置
const config = {
	//入口js文件
	entry: entries,
	//输出js文件
	output: {
		filename: 'js/[name].js?[chunkhash:8]',
		chunkFilename: 'js/[name].js?[chunkhash:8]',
		path: path.resolve(ROOT, 'dist'),
		publicPath: publicPath
	},
	module: {
		// @see https://doc.webpack-china.org/configuration/module/#module-noparse
		// 排除不需要 webpack 解析的文件，提高速度
		/* noParse: function (content) {
			return /jquery|zepto/.test(content);
		}, */
		noParse: /jquery|lodash/,
		rules: [
			{
				test: /\.js$/i,
				exclude: /(node_modules|bower_components)/,
				use: {
					loader: 'babel-loader?id=js',
					options: {
						presets: ['env']
					}
				}
			},
			{
				test: /\.(less|css)$/i,
				use: ExtractTextPlugin.extract({
					fallback: 'style-loader?id=styles',
					use: [{
						loader: 'css-loader?id=styles',
						options: {
							minimize: IsProduction
						}
					},
					{
						loader: 'less-loader?id=styles'
					},
					{
						loader: 'postcss-loader?id=styles',
						options: {
							config: {
								path: PostcssConfigPath
							}
						}
					}
					],
					publicPath: staticCss
				})
			},
			{
				test: /\.(png|jpe?g|gif|svg)$/i,
				use: [
					{
						loader: 'url-loader',
						options: {
							limit: 100,
							publicPath: staticImg,//staticImg + extraPath, //正式环境输出正式地址
							outputPath: function (path) {
								return path.replace('src/images', 'images');
							},
							name: '[path][name].[ext]?[hash:8]'
						}
					}
				]
			}
		]
	},
	resolve: {
		modules: [
			...resolveModules
		],
		alias: {
			'@': resolve('src/js')
		},
		extensions: ['.js', '.vue', '.less', '.jsx']
	},
	plugins: configPlugins,
	// @see http://webpack.github.io/docs/webpack-dev-server.html
	// @see http://www.css88.com/doc/webpack2/configuration/dev-server/
	devServer: {
		contentBase: [
			path.join(ROOT, 'src/')
		],
		open:false,
		disableHostCheck: true,  // https://stackoverflow.com/questions/43650550/invalid-host-header-in-when-running-react-app
		hot: false,
		host: '0.0.0.0',
		port: 6060
	}
};

module.exports = config;